﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using System.Xml;
using System.IO;

namespace myDiet
{
    public partial class LoginPage : PhoneApplicationPage
    {
        App app = App.Current as App;               //set "app" for global variable [user profile]
        UserData userItem;                          //set new "UserData" class, name >> userItem

        PageOrientation lastOrientation;            //set "lastOrientation" for detect page orientation
        public LoginPage()
        {
            InitializeComponent();
            this.OrientationChanged += new EventHandler<OrientationChangedEventArgs>(LoginPage_OrientationChanged);
            lastOrientation = this.Orientation;
        }

        void LoginPage_OrientationChanged(object sender, OrientationChangedEventArgs e)         //detect and handle page orientation
        {
            PageOrientation newOrientation = e.Orientation;
            Debug.WriteLine("New orientation: " + newOrientation.ToString());

            RotateTransition transitionElement = new RotateTransition();
            switch (newOrientation)
            {
                case PageOrientation.Landscape:
                case PageOrientation.LandscapeRight:
                    // Come here from PortraitUp (i.e. clockwise) or LandscapeLeft?
                    if (lastOrientation == PageOrientation.PortraitUp)
                        transitionElement.Mode = RotateTransitionMode.In90Counterclockwise;
                    else
                        transitionElement.Mode = RotateTransitionMode.In180Clockwise;
                    break;
                case PageOrientation.LandscapeLeft:
                    // Come here from LandscapeRight or PortraitUp?
                    if (lastOrientation == PageOrientation.LandscapeRight)
                        transitionElement.Mode = RotateTransitionMode.In180Counterclockwise;
                    else
                        transitionElement.Mode = RotateTransitionMode.In90Clockwise;
                    break;
                case PageOrientation.Portrait:
                case PageOrientation.PortraitUp:
                    // Come here from LandscapeLeft or LandscapeRight?
                    if (lastOrientation == PageOrientation.LandscapeLeft)
                        transitionElement.Mode = RotateTransitionMode.In90Counterclockwise;
                    else
                        transitionElement.Mode = RotateTransitionMode.In90Clockwise;
                    break;
                default:
                    break;
            }

            // Execute the transition
            PhoneApplicationPage phoneApplicationPage = (PhoneApplicationPage)(((PhoneApplicationFrame)Application.Current.RootVisual)).Content;
            ITransition transition = transitionElement.GetTransition(phoneApplicationPage);
            transition.Completed += delegate
            {
                transition.Stop();
            };
            transition.Begin();

            lastOrientation = newOrientation;
        }

        private void login_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri("http://" + app.url + "/MyDiet/profile_record.php", UriKind.RelativeOrAbsolute));  //load xml from web service [localhost]
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                XElement user = XElement.Parse(e.Result);
                var items = from item in user.Descendants("user")          //start at "user" element
                            where item.Element("username").Value == usernameTextBox.Text
                            select userItem = new UserData
                            {
                                //feed value of elements to new UserData class
                                Uid = item.Element("uid").Value,
                                UserName = item.Element("username").Value,
                                Password = item.Element("password").Value,
                                Age = item.Element("age").Value,
                                Name = item.Element("name").Value,
                                Gender = item.Element("gender").Value,
                                Email = item.Element("email").Value,
                                BirthDay = item.Element("birthday").Value,
                                Blood = item.Element("blood").Value,
                                Disease = item.Element("disease").Value,
                                Height = item.Element("height").Value,
                                Weight = item.Element("weight").Value,
                                Limit = item.Element("limit_cal").Value
                            };

                int count = items.Count();         //count items for check username and password
                if (count == 1)
                {
                    //set global varible = UserData class  
                    app.UID = userItem.Uid;
                    app.LoginName = userItem.UserName;
                    app.PassWord = userItem.Password;
                    app.Age = userItem.Age;
                    app.Name = userItem.Name;
                    app.Gender = userItem.Gender;
                    app.Email = userItem.Email;
                    app.BirthDay = userItem.BirthDay;
                    app.Blood = userItem.Blood;
                    app.Disease = userItem.Disease;
                    app.Height = userItem.Height;
                    app.Weight = userItem.Weight;
                    app.Limit = userItem.Limit;

                    if (app.PassWord == PasswordBox.Password)           //check password
                    {
                        CreateUser();
                        NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));      //if correct, navigate to MainPage.xaml
                    }
                    else MessageBox.Show("The password you entered is incorrect. Please try again");
                }
                else MessageBox.Show("Username Invalid. Please try again");
            }
        }


        //******************************** Create xml file for check login [userXML.xml] **************************************
        public void CreateUser()
        {
            // set variable refer to IsolatedStorageFile
            using (IsolatedStorageFile myIsolated = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // set variable refer to IsolatedStorageFileStream
                using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("userXML.xml", FileMode.Create, myIsolated))
                {
                    // set variable refer to XmlWriterSetting
                    XmlWriterSettings setting = new XmlWriterSettings();
                    setting.Indent = true;

                    // set variable refer to XmlWriter
                    using (XmlWriter writer = XmlWriter.Create(isoStream, setting))
                    {
                        // create element and value
                        writer.WriteStartElement("p", "profile", "upn:profile");

                        writer.WriteStartElement("user");

                        writer.WriteStartElement("uid");
                        writer.WriteString(userItem.Uid);
                        writer.WriteEndElement();

                        writer.WriteStartElement("username");
                        writer.WriteString(userItem.UserName);
                        writer.WriteEndElement();

                        writer.WriteStartElement("password");
                        writer.WriteString(userItem.Password);
                        writer.WriteEndElement();

                        writer.WriteStartElement("age");
                        writer.WriteString(userItem.Age);
                        writer.WriteEndElement();

                        writer.WriteStartElement("name");
                        writer.WriteString(userItem.Name);
                        writer.WriteEndElement();

                        writer.WriteStartElement("gender");
                        writer.WriteString(userItem.Gender);
                        writer.WriteEndElement();

                        writer.WriteStartElement("email");
                        writer.WriteString(userItem.Email);
                        writer.WriteEndElement();

                        writer.WriteStartElement("birthday");
                        writer.WriteString(userItem.BirthDay);
                        writer.WriteEndElement();

                        writer.WriteStartElement("blood");
                        writer.WriteString(userItem.Blood);
                        writer.WriteEndElement();

                        writer.WriteStartElement("disease");
                        writer.WriteString(userItem.Disease);
                        writer.WriteEndElement();

                        writer.WriteStartElement("height");
                        writer.WriteString(userItem.Height);
                        writer.WriteEndElement();

                        writer.WriteStartElement("weight");
                        writer.WriteString(userItem.Weight);
                        writer.WriteEndElement();

                        writer.WriteStartElement("limit_cal");
                        writer.WriteString(userItem.Limit);
                        writer.WriteEndElement();

                        writer.WriteEndElement();

                        // end document
                        writer.WriteEndDocument();

                        // writer to file
                        writer.Flush();
                    }
                }

                //#############################################################################################################
                // ******************************** for check xml file show to MessageBox *************************************
                string test;
                try
                {
                    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("userXML.xml", FileMode.Open);
                        using (StreamReader reader = new StreamReader(isoFileStream))
                        {
                            test = reader.ReadToEnd();
                            MessageBox.Show(test, "result", MessageBoxButton.OK);
                        }
                    }
                }
                catch { MessageBox.Show("File not found !"); }
                //*************************************************************************************************************
                //#############################################################################################################
            }
        }
        //*************************************************************************************************************

        //clear page and exit
        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (NavigationService.CanGoBack)
                {
                    while (NavigationService.RemoveBackEntry() != null)
                    {
                        NavigationService.RemoveBackEntry();
                    }
                }   
        }
    }
}
